import { addUserChannelsApi, delUserChannelsApi, getChannelsApi, getUserChannelsApi } from '@/api/channels';
import store, { AppDispatch } from '..';
import { Toast } from 'antd-mobile';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';
import { channelsType } from '../reducer/channels';

export const getChannelsAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getChannelsApi();
    dispatch({ type: 'channels/setChannels', payload: res.data.channels });
  };
};
export const getUserChannelsAction = () => {
  return async (dispatch: AppDispatch) => {
    // 判断是否用户登录
    if (hasToken()) {
      const res = await getUserChannelsApi();
      dispatch({ type: 'channels/setUserChannels', payload: res.data.channels });
      return;
    }
    // 未登录 从本地获取
    const localUserChannels = getLocalChannels();
    if (localUserChannels.length) {
      dispatch({ type: 'channels/setUserChannels', payload: localUserChannels });
      return;
    }
    // 未登录 本地也没有 从推荐获取 11条
    const res = await getChannelsApi();
    const userList = res.data.channels.slice(0, 11);
    dispatch({ type: 'channels/setUserChannels', payload: userList });
    setLocalChannels(userList);
  };
};

export const addUserChannelsAction = (newChannels: channelsType) => {
  return async (dispatch: AppDispatch) => {
    //判断登录
    if (hasToken()) {
      await addUserChannelsApi(newChannels);
      //没有登录 本地添加
    } else {
      setLocalChannels([...getLocalChannels(), newChannels]);
    }
    dispatch({ type: 'channels/addUserChannels', payload: newChannels.id });
    Toast.show({ content: '添加成功' });
  };
};
export const delUserChannelsAction = (id: number) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    //提示推荐不能删
    if (id === 0) {
      return Toast.show({ content: '推荐频道不能删' });
    }
    const { userChannels } = getState().channels;
    //提示长度不能少于五
    if (userChannels.length <= 5) {
      return Toast.show({ content: '至少保留五个频道' });
    }
    //判断登录
    if (hasToken()) {
      await delUserChannelsApi(id);
      //没有登录 本地删除
    } else {
      const newChannels = getLocalChannels().filter((item) => item.id !== id);
      setLocalChannels(newChannels);
    }
    dispatch({ type: 'channels/delUserChannels', payload: id });
    Toast.show({ content: '删除成功' });
  };
};

export const setCurrentIdAction = (id: number) => ({
  type: 'channels/setCurrentId',
  payload: id,
});
